package com.lucy.viewer.onlyoffice.provider;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.lucy.viewer.constant.ViewerServiceEnum;
import com.lucy.viewer.event.FileEditedEvent;
import com.lucy.viewer.onlyoffice.constant.DocumentStatus;
import com.lucy.viewer.onlyoffice.entity.Document;
import com.lucy.viewer.onlyoffice.entity.DocumentEditCallback;
import com.lucy.viewer.onlyoffice.entity.DocumentEditCallbackResponse;
import com.lucy.viewer.onlyoffice.entity.DocumentEditParam;
import com.lucy.viewer.onlyoffice.service.DocumentService;
import com.lucy.viewer.params.ViewerFile;
import com.lucy.viewer.service.ViewerAuthService;
import com.lucy.viewer.service.ViewerFileService;
import com.lucy.viewer.service.ViewerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * @author kindear
 * onlyoffice 文件预览编辑服务生产者
 */
@Slf4j
@Service
public class OnlyOfficeViewerServiceImpl implements ViewerService {
    @Value("${server.host}")
    private String serverHost;

    @Autowired
    DocumentService documentService;

    @Autowired
    ViewerAuthService viewerAuthService;

    @Autowired
    ViewerFileService viewerFileService;

    @Resource
    ApplicationContext context;

    @Override
    public ViewerServiceEnum service() {
        return ViewerServiceEnum.ONLY_OFFICE;
    }

    @Override
    public ModelAndView loadPreviewView(String documentKey, HttpServletResponse response) throws IOException {
        Document document = documentService.getDocument(documentKey);
        // 修改文件下载地址
        document.setUrl(serverHost+document.getUrl());
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("viewer");
        modelAndView.addObject("document",document);
        return modelAndView;
    }

    @Override
    public ModelAndView loadEditorView(String documentKey, HttpServletResponse response) throws IOException {

        DocumentEditParam documentEditParam = documentService.buildDocumentEditParam(viewerAuthService.getUserId(), viewerAuthService.getUserName());
        Document document = documentService.getDocument(documentKey);
        // 修改文件下载地址
        document.setUrl(serverHost+document.getUrl());
        //log.info("下载地址为:{}",document.getUrl());
        if (documentService.canEdit(document)){
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("editor");
            modelAndView.addObject("document",document);
            modelAndView.addObject("documentEditParam",documentEditParam);
            return modelAndView;
        }else {
            // 不满足编辑条件 返回预览
            response.sendRedirect("/viewer/preview/"+documentKey);
            return null;
        }
    }

    @Override
    public Object editorCallBack(Map<String, Object> map) {
        DocumentEditCallback callback = BeanUtil.fillBeanWithMap(map,new DocumentEditCallback(),false);
        log.info("---onlyoffice文件编辑回调---");
        // 需要保存时写出文件
        if (callback.getStatus() == DocumentStatus.READY_FOR_SAVING.getCode() || callback.getStatus() == DocumentStatus.BEING_EDITED_STATE_SAVED.getCode()) {
            //Document document = documentService.getDocument(callback.getKey());
            // 获取文件Key
            String fileKey = callback.getKey();
            ViewerFile file = viewerFileService.getViewerFile(fileKey);
//            String filePath = file.getPath();
//            File saveFile = FileUtil.touch(filePath);
//            boolean success = false;
            try {
                HttpResponse response = HttpRequest.get(callback.getUrl()).execute();
                // 获取流
                InputStream stream = response.bodyStream();
                // 写入覆盖
                //response.writeBody(saveFile);
                // 更新文件流
                //viewerFileService.updateViewerFile(FileUtil.getInputStream(saveFile), document.getKey());
                viewerFileService.updateViewerFile(stream, fileKey);
                // 发布文件编辑完成事件
                context.publishEvent(new FileEditedEvent(this,file));
            }catch (Exception e){
                log.error("---onlyoffice文件编辑保存失败---");
            }

            //boolean success = documentService.saveDocumentFile(callback.getKey(), callback.getUrl());
            log.info("---onlyoffice文件编辑已保存---");
//            if (!success) {
//                return DocumentEditCallbackResponse.failue();
//            }
        }
        return DocumentEditCallbackResponse.success();
    }
}
